;(function(window, document) {
    angular
      .module('app')
      .controller('payCallbackController', payCallbackController);

    payCallbackController.$inject = [
      'payPayokFactory',
      'randomWordFactory',
      'globalService',
      '$cookies',
      '$stateParams',
      '$state'
    ];

    function payCallbackController (payPayokFactory, randomWordFactory, globalService, $cookies, $stateParams, $state) {
      if ($stateParams.orderid === globalService.orderid) {
          // 向后台发送
          payPayokFactory.setOrderid($stateParams.orderid);
          payPayokFactory.setPayorderid($stateParams.payorderid);
          payPayokFactory.setPaytype($stateParams.paytype);
          payPayokFactory.setSign($stateParams.sign);

          payPayokFactory.payPayokPromise().then(payPayokPromiseSuccess, payPayokPromiseFail);
      } else {
          alert('订单号不一致');
          history.go(-1);
      }

      function payPayokPromiseSuccess(data) {
          switch (data.returncode) {
              case 0:
                  // 生成随机数
                  var randomKey = randomWordFactory.getRandomWord(true, 8, 12);
                  $cookies.putObject(randomKey, {
                      username: data.username,
                      password: data.password
                  }, {expires: new Date(Date.now() + 1800000)});
                  // 跳转
                  $state.go('accountDaylist.details.payok', {accountdayid: globalService.dayid, key: randomKey});
                  break;
              case -1:
                  alert('已购买同类账号');
                  history.go(-1);
                  break;
              case -2:
                  alert('签名失败');
                  history.go(-1);
                  break;
              case -3:
                  alert('订单状态错误');
                  history.go(-1);
                  break;
              case -999:
                  alert('系统维护升级中');
                  history.go(-1);
                  break;
          }
      }

      function payPayokPromiseFail(err) {
          alert(err);
          history.go(-1);
      }
    }

})(window, document);
